<template>
  <!-- 模具使用寿命表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    :width="props.isReadonly ? '800px' : '500px'"
    draggable
    @close="closeDialog"
  >
    <el-descriptions
      class="margin-top"
      title=""
      :column="2"
      size="large"
      v-show="props.isReadonly"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">模具</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.assetCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">设备</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.equipCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">使用模数</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.useQuantity }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">累计模数</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.totalQuantity }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">数据来源</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ useDictionary("MouldLifetimeSource", formData?.dateSource) }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">登记时间</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.registrationTime }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">创建时间</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.createTime }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">创建人</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.createdUserName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.remarks }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="160"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="模具" prop="assetId" label-width="80px">
            <el-select
              style="width: 100%"
              v-model="formData.assetId"
              placeholder="请选择模具"
              clearable
              filterable
              :filter-method="customMouldFilter"
              @change="changeAsset"
            >
              <el-option
                v-for="item in filteredMouldList"
                :key="item.id"
                :label="item.assetName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="设备" prop="equipId" label-width="80px">
            <el-select
              style="width: 100%"
              v-model="formData.equipId"
              placeholder="请选择设备"
              filterable
              :filter-method="customEquipFilter"
              clearable
              @change="changeEquip"
            >
              <el-option
                v-for="item in filteredEquipList"
                :key="item.id"
                :label="item.equipCode"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="使用模数" prop="useQuantity" label-width="80px">
            <el-input
              v-model="formData.useQuantity"
              placeholder="请输入使用模数"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="登记时间"
            prop="registrationTime"
            label-width="80px"
          >
            <el-date-picker
              v-model="formData.registrationTime"
              type="datetime"
              placeholder="请选择登记时间"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks" label-width="80px">
            <el-input
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { validateNumber } from "@/utils/commonHooks";
import { useDictionary } from "../../../../../utils/useTable";
import { debounce } from "lodash-es"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEAMMOULDLIFETIMERECORDADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  assetId: [
    { required: true, message: "请选择模具", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  equipId: [
    { required: true, message: "请选择设备", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  useQuantity: [
    { required: true, message: "请输入使用模数", trigger: "blur" },
    { validator: validateNumber, trigger: "blur" },
  ],
  totalQuantity: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  assetId: "",
  assetCode: "",
  assetName: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  useQuantity: "",
  totalQuantity: "",
  dateSource: "1",
  registrationTime: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        assetId,
        assetCode,
        assetName,
        equipId,
        equipCode,
        equipName,
        useQuantity,
        totalQuantity,
        dateSource,
        registrationTime,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        assetId,
        assetCode,
        assetName,
        equipId,
        equipCode,
        equipName,
        useQuantity,
        totalQuantity,
        dateSource,
        registrationTime,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.assetId = "";
  formData.assetCode = "";
  formData.assetName = "";
  formData.equipId = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.useQuantity = "";
  formData.totalQuantity = "";
  formData.dateSource = "1";
  formData.registrationTime = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 模具使用寿命保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/eam/eammouldlifetimerecord/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
const mouldList = ref([]);
const filteredMouldList = ref([]);
async function getMouldList() {
  const { data } = await request({
    url: "/eam/mouldAssetInfo/getList",
    method: "post",
    data: {},
  });
  mouldList.value = data;
  filteredMouldList.value = [...data];
}
const customMouldFilter = debounce((query: any) => {
  if (!query) {
    filteredMouldList.value = [...mouldList.value];
    return;
  }
  filteredMouldList.value = mouldList.value.filter((option: any) =>
    option.assetName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);
const equipList = ref([]);
const filteredEquipList = ref([]);
async function getEquipList() {
  const { data } = await request({
    url: "/mdm/mdmequipinfo/getList",
    method: "post",
    data: {},
  });
  equipList.value = data;
  filteredEquipList.value = [...data];
}

const customEquipFilter = debounce((query: any) => {
  if (!query) {
    filteredEquipList.value = [...equipList.value];
    return;
  }
  filteredEquipList.value = equipList.value.filter((option: any) =>
    option.equipCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300);
onMounted(() => {
  getMouldList();
  getEquipList();
});

const changeAsset = () => {
  if (formData.assetId) {
    const find = mouldList.value.find((item) => item.id === formData.assetId);
    formData.assetCode = find?.assetCode;
    formData.assetName = find?.assetName;
  } else {
    formData.assetCode = "";
    formData.assetName = "";
  }
};

const changeEquip = () => {
  if (formData.equipId) {
    const find = equipList.value.find((item) => item.id === formData.equipId);
    formData.equipCode = find?.equipCode;
    formData.equipName = find?.equipName;
  } else {
    formData.equipCode = "";
    formData.equipName = "";
  }
};
</script>
